<?php

namespace app\store\service;

use app\store\model\GroupActivity;
use think\facade\Db;
use think\facade\Queue;

class GroupActivityService
{
    /**
     * 获取拼团活动列表
     * */
    public function getGroupActivityList($param)
    {   
        $store_id = session('store_id');

        $model = new GroupActivity();
        $query = $model->withOutField('rule_content,delete_time')->where('store_id',$store_id);

        if(isset($param['status']) && $param['status'] != ''){
            $query->where('status',$param['status']);
        }

        if(!empty($param['start_time']) && !empty($param['end_time'])){

            $query->whereTime('start_time', '<=', $param['start_time'])
                  ->whereTime('end_time', '>=', $param['end_time']);
        }

        if(!empty($param['keyword'])){
            $query->whereLike('activity_title',"%{$param['keyword']}%");
        }


        $groupActivity = $query->order(['end_time' => 'asc','id' => 'desc'])->paginate();
        
        return  $groupActivity;
        
    }



    /**
     * 获取拼团活动选项
     * */
    public function getGroupActivityOptions($param)
    {
        $store_id = session('store_id');

        $model = new GroupActivity();
        $query = $model->withOutField('rule_content,delete_time')
                      ->where('store_id',$store_id)
                      ->where('end_time','>',time());


        if(!empty($param['start_time']) && !empty($param['end_time'])){

            $query->whereTime('start_time', '<=', $param['start_time'])
                ->whereTime('end_time', '>=', $param['end_time']);
        }

        if(!empty($param['keyword'])){
            $query->whereLike('activity_title',"%{$param['keyword']}%");
        }


        $groupActivity = $query->order(['end_time' => 'asc','id' => 'desc'])->paginate();

        return  $groupActivity;

    }

    /**
     * 获取拼团活动详情
     * */
    public function findGroupActivity($id)
    {
        $groupActivity = Db::name('group_activity')->withOutField('create_time,update_time,delete_time')
                        ->withAttr('success_rule',function ($value){
                            return json_decode($value,true);
                        })->withAttr('fail_rule',function ($value){
                            return json_decode($value,true);
                        })->where('id',$id)
                        ->find();

        $cols = Db::name('group_goods')
                    ->field('a.id as goods_id,a.goods_name,a.main_image')
                    ->alias('a')
                    ->join('group_activity_goods b','a.id=b.group_goods_id')
                    ->where('b.group_activity_id',$id)
                    ->select();
        $goods = [];
        if (!$cols->isEmpty()){
            $goods = $cols->toArray();
        }

        $groupActivity['goods'] = $goods;

    
        return $groupActivity;
        
    }


    /**
     * 保存拼团活动
     * */

    public static function saveGroupActivity($data)
    {
        $data['store_id'] = session('store_id');

        Db::startTrans();
        try {
            $model =  GroupActivity::create($data);
            $goods = static::formatAllowGoods($data['allow_goods'],$model['id']);
            Db::name('group_activity_goods')->insertAll($goods);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return  false;
        }

    }


    /**
     * 更新拼团活动
     * */

    public static function updateGroupActivity($data)
    {
        $data['store_id'] = session('store_id');
        Db::startTrans();
        try {
            $model =  GroupActivity::update($data);
            $goods = static::formatAllowGoods($data['allow_goods'],$model['id']);
            Db::name('group_activity_goods')->where('group_activity_id',$model['id'])->delete();
            Db::name('group_activity_goods')->insertAll($goods);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return  false;
        }

    }

    /**
     * 格式化可用商品
     * */
    public static function formatAllowGoods($allow_goods,$group_activity_id)
    {
        $arr = json_decode($allow_goods,true);

        $goods = [];
        foreach ($arr as $k => $v){
            $goods[$k]['group_goods_id'] = $v['goods_id'];
            $goods[$k]['group_activity_id'] = $group_activity_id;
        }

        return $goods;
    }

    /**
     * 删除活动商品
     * */

    public static function deleteGoods($id)
    {
        $res = Db::name('group_activity_goods')->where('id',$id)->delete();

        return $res;
    }


    /**
     * 获取活动记录
     * */
    public static function getActivityRecord($group_activity_id)
    {
        $list  = Db::name('group_activity_record')
            ->alias('a')
            ->field('a.user_id,a.group_order_id,b.trade_method,b.trade_fee,b.out_trade_no')
            ->join('group_order_trade b','a.group_order_id=b.group_order_id')
            ->where([
                'a.group_activity_id' => $group_activity_id,
                'b.trade_status' => 1,
            ])->select();

        if ($list->isEmpty()){
            return [];
        }

        return  $list->toArray();
    }

    /**
     * 更新活动成功记录
     * */
    public static function changeSuccessActivityRecord($user_id,$group_activity_id,$success_gift)
    {
        $result = Db::name('group_activity_record')
            ->where([
                'user_id' => $user_id,
                'group_activity_id' => $group_activity_id
            ])->update($success_gift);

        return $result;
    }

    /**
     * 更新活动失败记录
     * */
    public static function changeFailActivityRecord($user_ids,$group_activity_id,$fail_gift)
    {

        $result = Db::name('group_activity_record')
                    ->whereIn('user_id',$user_ids)
                    ->where('group_activity_id',$group_activity_id)
                    ->update($fail_gift);
        return $result;
    }

    /**
     * 活动结算
     * */
    public static function finishGroupActivity($group_activity,$records)
    {
        $index = array_rand($records);

        $user_id = $records[$index]['user_id'];
        unset($records[$index]);
        $user_ids = array_column($records,'user_id');

        $success = $group_activity['success_rule'];
        $fail = $group_activity['fail_rule'];

        $success_gift = [];
        if ($success['integral']>0){
            $success_gift['integral'] = $success['integral'];
        }

        if ($success['balance']>0){
            $success_gift['balance'] = $success['balance'];
        }

        $success_gift['status'] = 2;


        $fail_gift = [];
        if ($fail['integral']>0){
            $fail_gift['integral'] = $fail['integral'];

        }

        if ($fail['balance']>0){
            $fail_gift['balance'] = $fail['balance'];
        }

        $fail_gift['status'] = -1;

        Db::startTrans();
        try {
            /**
             * 修改成功记录
             * */
            GroupActivityService::changeSuccessActivityRecord($user_id,$group_activity['id'],$success_gift);

            /**
             * 修改失败记录
             * */
            GroupActivityService::changeFailActivityRecord($user_ids,$group_activity['id'],$fail_gift);
            Db::name('group_activity')->where('id',$group_activity['id'])->update(['status'=>2]);
            Db::commit();
            return [
                'store_id' => $group_activity['store_id'],
                'group_activity_id' => $group_activity['id'],
                'user_id' => $user_id,
                'success_gift' => $success_gift,
                'user_ids' => $user_ids,
                'fail_gift' => $fail_gift,
                'group_orders' => $records
            ];
        }catch (\Exception $e){
            Db::rollback();
            return  [];
        }
    }


    /**
     * 成功奖励余额或积分加入队列
     * */

    public static function saveSuccessAwardQueue($user_id,$success_gift)
    {
        /**
         * 成功奖励
         * */
        if (isset($success_gift['integral'])){
            Queue::push('app\store\job\Account@integral',[
                'user_id' => $user_id,
                'desc' => '拼团活动奖励',
                'change_type'=>1,
                'integral' => $success_gift['integral']
            ],'userAccount');
        }

        if (isset($success_gift['balance'])){
            Queue::push('app\store\job\Account@balance',[
                'user_id' => $user_id,
                'desc' => '拼团活动奖励',
                'change_type'=>1,
                'balance' => $success_gift['balance']
            ],'userAccount');
        }
    }

    /**
     * 失败奖励余额或积分加入队列
     * */

    public static function saveFailAwardQueue($user_ids,$fail_gift)
    {
        /**
         * 失败奖励
         * */
        foreach ($user_ids as $v){

            if (isset($fail_gift['integral'])){
                Queue::push('app\store\job\Account@integral',[
                    'user_id' => $v,
                    'desc' => '拼团活动奖励',
                    'change_type'=>1,
                    'integral' => $fail_gift['integral']
                ],'userAccount');
            }

            if (isset($fail_gift['balance'])){
                Queue::push('app\store\job\Account@balance',[
                    'user_id' => $v,
                    'desc' => '拼团活动奖励',
                    'change_type'=>1,
                    'balance' => $fail_gift['balance']
                ],'userAccount');
            }

        }
    }


    /**
     * 失败退款
     * */

    public static function saveFailRefundQueue($store_id,$group_orders)
    {
        $config = static::getPaymentConfig($store_id);
        foreach ($group_orders as $v) {
            $queueRst = [
                'group_order_id' => $v['group_order_id'],
                'trade_method' => $v['trade_method'],
                'out_trade_no' => $v['out_trade_no'],
                'config' => $config[$v['trade_method']],
                'trade_fee' => $v['trade_fee']
            ];

            $rst = Queue::push('app\store\job\Refund',$queueRst ,'userRefund');

            echo '获取支付信息$$queueRst'. $rst;
        }
    }


    /**
     * 获取支付信息
     * */
    public static function getPaymentConfig($store_id)
    {

        $paymentConfig = Db::name('payment_config')
            ->field('type,config')
            ->where('store_id' ,$store_id)
            ->withAttr('config',function ($value){
                return json_decode($value,true);
            })->limit(2)
            ->select();

        if (empty($paymentConfig)){
            return  [];
        }

        $config = [];

        foreach ($paymentConfig as $v){
            $config[$v['type']] = $v['config'];
        }

        return  $config;
    }
}